package com.jerry.boot.business.auth;

import com.jerry.boot.business.auth.pojo.AuthDto;
import com.jerry.boot.business.auth.pojo.LoginReq;
import com.jerry.boot.business.auth.pojo.ReLoginDto;
import com.jerry.boot.business.user.User;
import com.jerry.boot.business.user.UserService;
import com.jerry.boot.business.user.pojo.UserInfo;
import com.jerry.boot.core.JConstant;
import com.jerry.boot.core.base.JConfigureProperties;
import com.jerry.boot.core.mvc.JsonResult;
import com.jerry.boot.core.web.ServletContextHelper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Resource
    private AuthService authService;

    @Resource
    private JConfigureProperties jConfigureProperties;

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public AuthDto login(@RequestBody @Valid LoginReq loginReq) {
        return authService.login(loginReq);
    }

    @GetMapping("/yzm")
    public String getYzm() {
        return authService.getYzm();
    }

    @GetMapping("/rsa-publicKey")
    public String getRsaPublicKey() {
        return jConfigureProperties.getRsaPublicKey();
    }

    @GetMapping("/logout")
    public JsonResult logOut() {
        authService.logout();
        return JsonResult.ok();
    }

    @PostMapping("/relogin")
    public AuthDto reLogin(@RequestBody @Valid ReLoginDto reLoginDto) {
        return authService.reLogin(reLoginDto);
    }

    @GetMapping("/login-info")
    public UserInfo loginInfo() {
        AuthDto authDto = (AuthDto) ServletContextHelper.getSession().getAttribute(JConstant.AUTH_USER_KEY);
        User user = userService.getUserByUsername(authDto.getUsername());
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setGender(user.getGender());
        userInfo.setUsername(user.getUsername());
        userInfo.setLastLoginTime(user.getLastLoginTime());
        return userInfo;
    }
}
